import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

class Message{
//    确保java代码中类/属性的名字与 json 中名字相对应
    public String from;
    public String to;
    public String message;
    public String toString() {
        return "Message{from = " + from + ", to = " + to + ", message = " + message + "}";
    }
}
@WebServlet("/message")
public class MessageServlet extends HttpServlet {
    //        读取前端发来的信息  把数据保存在服务器当中
    List<Message> messageList = new ArrayList<>();//存储 前端发来的消息
    ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //        使用ObjectMapper从HttpServletRequest的输入流中读取JSON数据。
//        req.getInputStream()提供了请求体的原始字节流
        Message message = objectMapper.readValue(req.getInputStream(), Message.class);
//        readValue方法把JSON字符串转换成Java的Request对象。
        System.out.println("收到请求发来的消息:"+message);
//      存储消息  1.存储在内存中(重启 重连服务器则会消失)  2.数据库 持久化存储
        messageList.add(message);

//        返回响应
        resp.setStatus(200);
        //resp.setContentType("application/json;charset=utf8");
        resp.getWriter().write(" 返回响应 OK! ");
    }
}
